package com.shuai.jit.security.filter;

import com.shuai.jit.entity.R;
import com.shuai.jit.utils.JwtUtil;
import com.shuai.jit.utils.ResponseUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
import org.springframework.util.StringUtils;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * <p>
 * 访问过滤器
 * </p>
 *
 * @author qy
 * @since 2019-11-08
 */
@Slf4j
public class MyBasicAuthenticationFilter extends BasicAuthenticationFilter {

    private JwtUtil jwtUtils;
    private RedisTemplate<String,Object> redisTemplate;


    public MyBasicAuthenticationFilter(AuthenticationManager authManager, JwtUtil jwtUtils, RedisTemplate<String,Object> redisTemplate) {
        super(authManager);
        this.jwtUtils = jwtUtils;
        this.redisTemplate = redisTemplate;
    }

    /**
     * 拦截器 ,第一步，开始拦截
     * @param req
     * @param res
     * @param chain
     * @throws IOException
     * @throws ServletException
     */
    @Override
    protected void doFilterInternal(HttpServletRequest req, HttpServletResponse res, FilterChain chain)
            throws IOException, ServletException {
        log.info("================="+req.getRequestURI());
        //这个请求需要拦截
        UsernamePasswordAuthenticationToken authentication = null;
        try {
            //开始认证
            authentication = getAuthentication(req);
        } catch (Exception e) {
            ResponseUtil.out(res, R.error());
        }
        // 如果授权的内容不为空，直接放心
        if (authentication != null) {
            SecurityContextHolder.getContext().setAuthentication(authentication);
        } else {
            //没有权限，返回报错信息
            log.info("对不起用户验证错误");
            ResponseUtil.out(res, R.error());
            return;
        }
        //放行
        chain.doFilter(req, res);
    }

    /**
     *  第二步 ---- 认证是否有权限 ，验证token 是否有效
     * @param request
     * @return  null 没有权限，对不起，访问拒绝
     * 返回 UsernamePasswordAuthenticationToken ，该用户有权限
     */
    private UsernamePasswordAuthenticationToken getAuthentication(HttpServletRequest request) {
        //从header中取token
        String token = request.getHeader("token");

        // 如果token 没有的话，或者token 为空,token 还没有过期
        log.info("token "+token);
        if (token != null && !"".equals(token.trim()) && jwtUtils.verify(token)) {
            // 获取用户名
            String userName = jwtUtils.getClaim(token,"username");
            //从redis中查权限交给SpringSecurity
            List<String> permissionValueList = (List<String>) redisTemplate.opsForValue().get(userName);
            Collection<GrantedAuthority> authorities = new ArrayList<>();

            // 把查到的权限授权，权限为空
            if(permissionValueList!=null){
                for(String permissionValue : permissionValueList) {
                    if(StringUtils.isEmpty(permissionValue)) {
                        continue;
                    }
                    SimpleGrantedAuthority authority = new SimpleGrantedAuthority(permissionValue);
                    authorities.add(authority);
                }
                //如果用户名不为null
                if (!StringUtils.isEmpty(userName)) {
                    // 认证成功
                    return new UsernamePasswordAuthenticationToken(userName, token, authorities);
                }
            }
            return null;
        }
        return null;
    }
}
